package com.jic.market.service.impl;

import com.jic.common.base.vo.RestResult;
import com.jic.market.entity.PromotionEntity;
import com.jic.market.entity.PromotionRuleEntity;
import com.jic.market.entity.PromotionSingleRuleEntity;
import com.jic.market.entity.coupon.CouponConfig;
import com.jic.market.mapper.PromotionMerchantProductEntityMapper;
import com.jic.market.mapper.PromotionRuleEntityMapper;
import com.jic.market.mapper.PromotionSingleRuleEntityMapper;
import com.jic.market.mapper.coupon.CouponConfigMapper;
import com.jic.market.request.ProductOrderReqVo;
import com.jic.market.request.ProductOrderRestRequest;
import com.jic.market.response.ProductMarketProductResponse;
import com.jic.market.response.ProductMarketResponse;
import com.jic.market.service.ProductOrderMarketService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 接口实现类
 *
 * @author : 订单确认下单数据计算接口
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class ProductOrderMarketServiceImpl implements ProductOrderMarketService {

    @Autowired
    private PromotionMerchantProductEntityMapper promotionMerchantProductEntityMapper;
    @Autowired
    private ProductListApi productListApi;
    @Autowired
    private PromotionSingleRuleEntityMapper productEntityMapper;
    @Autowired
    private PromotionRuleEntityMapper promotionRuleEntityMapper;
    @Autowired
    private CouponConfigMapper couponConfigMapper;

    @Override
    public ProductMarketResponse preOrder(ProductOrderRestRequest productOrderRestRequest) {
        ProductMarketResponse productMarketResponse=new ProductMarketResponse();
        productMarketResponse.setCouponAmount(new BigDecimal(0));
        //初始化返回的对象
        List<ProductMarketProductResponse> marketResponseList=new ArrayList<>();
        //判断是否购物车下单
        if(null!=productOrderRestRequest && productOrderRestRequest.getIsCart()==1){
            for(ProductOrderReqVo productOrderReqVo:productOrderRestRequest.getProductOrders()){
                ProductMarketProductResponse productMarketProductResponse = queryProductMarketById(productOrderReqVo.getProductId(), productOrderReqVo.getNum());
                if(null!=productMarketProductResponse){
                    marketResponseList.add(productMarketProductResponse);
                }
            }
            //删除购物车信息，暂无
        }else{
            //直接下单
            for(ProductOrderReqVo productOrderReqVo:productOrderRestRequest.getProductOrders()){
                ProductMarketProductResponse productMarketProductResponse = queryProductMarketById(productOrderReqVo.getProductId(), productOrderReqVo.getNum());
                if(null!=productMarketProductResponse){
                    marketResponseList.add(productMarketProductResponse);
                }
            }
        }
        productMarketResponse.setProductResponseList(marketResponseList);
        //统计优惠信息
        if(CollectionUtils.isNotEmpty(marketResponseList)){
            //优惠金额求和
            BigDecimal sumDiscountPriceMoney = marketResponseList.stream().map(ProductMarketProductResponse::getDiscountPrice).reduce(BigDecimal.ZERO,BigDecimal::add);
            productMarketResponse.setDiscountAmount(sumDiscountPriceMoney);
            //支付金额求和
            BigDecimal sumPayAmountMoney = marketResponseList.stream().map(ProductMarketProductResponse::getMarketPrice).reduce(BigDecimal.ZERO,BigDecimal::add);
            productMarketResponse.setPayAmount(sumPayAmountMoney);
            //原价金额求和
            BigDecimal sumProductMoney = marketResponseList.stream().map(ProductMarketProductResponse::getProductPrice).reduce(BigDecimal.ZERO,BigDecimal::add);
            productMarketResponse.setTotalAmount(sumProductMoney);
            //减免运费金额求和
            BigDecimal sumFreMoney = marketResponseList.stream().map(ProductMarketProductResponse::getSubFreight).reduce(BigDecimal.ZERO,BigDecimal::add);
            productMarketResponse.setSubFreight(sumFreMoney);

            //判断是否有商品是包邮
            boolean bool = marketResponseList.stream().anyMatch(a -> a.getIsFreight()==1);
            productMarketResponse.setIsFreight(bool?1:0);
        }
        //判断是否有优惠券
        if(StringUtils.isNotEmpty(productOrderRestRequest.getCouponId())){
            CouponConfig couponConfig = couponConfigMapper.queryByCouponConfigByCode(productOrderRestRequest.getCouponId());
            if(null!=couponConfig){
                //判断商品抵扣类型
                if(couponConfig.getAmountDeductType()==0){
                    //判断是否满足使用条件
                    if(couponConfig.getUseTotalAmountLimit().longValue()<=productMarketResponse.getTotalAmount().longValue()){
                        //运费券
                        //判断优惠方式
                        if(couponConfig.getCouponMode()==0){
                            //金额券
                            BigDecimal subtract = productMarketResponse.getPayAmount().subtract(couponConfig.getCouponAmount());
                            productMarketResponse.setPayAmount(subtract);
                            //设置优惠金额
                            productMarketResponse.setDiscountAmount(productMarketResponse.getDiscountAmount().add(couponConfig.getCouponAmount()));
                            //设置优惠券金额
                            productMarketResponse.setCouponAmount(couponConfig.getCouponAmount());
                        }else{
                            //设置优惠金额
                            productMarketResponse.setDiscountAmount(productMarketResponse.getDiscountAmount().add(productMarketResponse.getPayAmount().subtract(productMarketResponse.getPayAmount().multiply(new BigDecimal(couponConfig.getDiscountNum())))));
                            //设置优惠券金额
                            productMarketResponse.setCouponAmount(productMarketResponse.getPayAmount().subtract(productMarketResponse.getPayAmount().multiply(new BigDecimal(couponConfig.getDiscountNum()))));
                            //折扣券
                            BigDecimal subtract = productMarketResponse.getPayAmount().multiply(new BigDecimal(couponConfig.getDiscountNum()));
                            productMarketResponse.setPayAmount(subtract);

                        }
                    }
                }
                else if(couponConfig.getAmountDeductType()==1){
                    //运费券
                    //判断优惠方式
                    if(couponConfig.getCouponMode()==0){
                       //金额券
                        BigDecimal subtract = productMarketResponse.getSubFreight().subtract(couponConfig.getCouponAmount());
                        productMarketResponse.setSubFreight(productMarketResponse.getSubFreight().add(subtract));
                        //设置优惠券金额
                        productMarketResponse.setCouponAmount(subtract);
                    }else{
                        //折扣券
                        BigDecimal subtract = productMarketResponse.getSubFreight().multiply(new BigDecimal(couponConfig.getDiscountNum()));
                        productMarketResponse.setSubFreight(productMarketResponse.getSubFreight().add(subtract));
                        //设置优惠券金额
                        productMarketResponse.setCouponAmount(subtract);
                    }
                }else if(couponConfig.getAmountDeductType()==2){
                    //代金券
                    //判断优惠方式
                    if(couponConfig.getCouponMode()==0){
                        //金额券
                        BigDecimal subtract = productMarketResponse.getPayAmount().subtract(couponConfig.getCouponAmount());
                        productMarketResponse.setPayAmount(subtract);
                        //设置优惠金额
                        productMarketResponse.setDiscountAmount(productMarketResponse.getDiscountAmount().add(couponConfig.getCouponAmount()));
                        //设置优惠券金额
                        productMarketResponse.setCouponAmount(couponConfig.getCouponAmount());
                    }
                }
            }
        }
        return productMarketResponse;
    }

    @Override
    public ProductMarketProductResponse queryProductMarketById(Long productId, Integer num) {
        ProductMarketProductResponse marketResponse=null;
        List<String> tips=new ArrayList<>();
        //查询商品信
        RestResult<ProductAfterInfoByIdResponse> productInfoData = productListApi.queryProductInfoById(productId);
        if(null!=productInfoData && null!=productInfoData.getData()){
            marketResponse=new ProductMarketProductResponse();
            ProductAfterInfoByIdResponse productInfo = productInfoData.getData();
            //判断商品是否存在
            if(null!=productInfo){
                marketResponse.setDiscountPrice(new BigDecimal(0));
                marketResponse.setMarketPrice(productInfo.getSalePriceWithTax().multiply(new BigDecimal(num)));
                marketResponse.setNum(Long.valueOf(num));
                marketResponse.setProductPrice(productInfo.getSalePriceWithTax().multiply(new BigDecimal(num)));
                marketResponse.setSubFreight(new BigDecimal(0));
                marketResponse.setIsFreight(0);
                marketResponse.setProductId(productId);
                //根据商品id，查询活动信息
                List<PromotionEntity> promotionEntityList = promotionMerchantProductEntityMapper.queryPromotionMerchant(productId);
                if(CollectionUtils.isNotEmpty(promotionEntityList)){
                    for(PromotionEntity promotionEntity:promotionEntityList){
                        //判断活动类型
                        if(promotionEntity.getPromType()==1){
                            //查询单一促销优惠信息
                            PromotionSingleRuleEntity promotionSingleRuleEntity = productEntityMapper.getEntityByPromotionIdAndMpId(promotionEntity.getId(), productId);
                            if(null!=promotionSingleRuleEntity){
                                //单一促销
                                if(promotionEntity.getFrontPromType()==1){
                                    //优惠金额
                                    marketResponse.setDiscountPrice(marketResponse.getDiscountPrice().add(marketResponse.getMarketPrice().subtract(promotionSingleRuleEntity.getContentValue().multiply(new BigDecimal(num)))));
                                    //特价促销 //直接替换原价
                                    marketResponse.setMarketPrice(promotionSingleRuleEntity.getContentValue().multiply(new BigDecimal(num)));
                                    tips.add("特价促销");
                                }else if(promotionEntity.getFrontPromType()==2){
                                    //优惠金额
                                    marketResponse.setDiscountPrice(marketResponse.getDiscountPrice().add(((marketResponse.getMarketPrice()).multiply(promotionSingleRuleEntity.getContentValue()))));
                                    //折扣促销 原价乘以折扣
                                    marketResponse.setMarketPrice(((marketResponse.getMarketPrice()).multiply(promotionSingleRuleEntity.getContentValue())));
                                    tips.add("折扣促销");
                                }else if(promotionEntity.getFrontPromType()==3){
                                    //优惠金额
                                    marketResponse.setDiscountPrice(marketResponse.getDiscountPrice().add((marketResponse.getMarketPrice()).subtract((promotionSingleRuleEntity.getContentValue().multiply(new BigDecimal(num))))));
                                    //直降促销 原价减去-直接价格
                                    marketResponse.setMarketPrice((marketResponse.getMarketPrice()).subtract((promotionSingleRuleEntity.getContentValue().multiply(new BigDecimal(num)))));
                                    tips.add("直降促销");
                                }                            }
                        }else if(promotionEntity.getPromType()==3){
                            //满额促销
                            //查询满量，满额，促销优惠信息
                            PromotionRuleEntity promotionRuleEntity = promotionRuleEntityMapper.queryPromotionRuleById(promotionEntity.getId());
                            if(null!=promotionRuleEntity){
                                if(promotionEntity.getFrontPromType()==6){
                                    //满额减 判断商品数量和单价总额，是否满足满额要求
                                    if(promotionRuleEntity.getConditionValue()/100<=marketResponse.getMarketPrice().longValue()){
                                        //优惠金额
                                        marketResponse.setDiscountPrice(marketResponse.getDiscountPrice().add(promotionRuleEntity.getContentValue().divide(new BigDecimal(100))));
                                        //总金额减去优惠抵扣金额
                                        marketResponse.setMarketPrice(marketResponse.getMarketPrice().subtract(promotionRuleEntity.getContentValue().divide(new BigDecimal(100))));
                                        tips.add("满额减");
                                    }
                                }else if(promotionEntity.getFrontPromType()==7){
                                    //满额折 判断商品数量和单价总额，是否满足满额要求
                                    if(promotionRuleEntity.getConditionValue()/100<=marketResponse.getMarketPrice().longValue()){
                                        //优惠金额
                                        BigDecimal subtract = marketResponse.getMarketPrice().subtract((marketResponse.getMarketPrice().multiply(promotionRuleEntity.getContentValue().divide(new BigDecimal(100)))));
                                        marketResponse.setDiscountPrice(marketResponse.getDiscountPrice().add(subtract));
                                        //总金额减去优惠抵扣金额
                                        marketResponse.setMarketPrice((marketResponse.getMarketPrice()).multiply(promotionRuleEntity.getContentValue().divide(new BigDecimal(100))));
                                        tips.add("满额折");
                                    }
                                }else if(promotionEntity.getFrontPromType()==19){
                                    //满额免运费
                                    if(promotionEntity.getFreightType()==1){
                                        //满多少元免运费
                                        //总金额减去优惠抵扣金额 商品单价价格*总数量
                                        if(marketResponse.getMarketPrice().longValue()>=promotionEntity.getFreightValue().longValue()){
                                            marketResponse.setMarketPrice(marketResponse.getMarketPrice());
                                            //包邮
                                            marketResponse.setIsFreight(1);
                                            tips.add("满额免运费");
                                        }
                                    }else if(promotionEntity.getFreightType()==2){
                                        //满x元减y元运费
                                        if(marketResponse.getMarketPrice().longValue()>=promotionEntity.getFreightValue().longValue()) {
                                            //优惠金额
                                            marketResponse.setMarketPrice(marketResponse.getMarketPrice());
                                            //优惠运费
                                            marketResponse.setSubFreight(promotionEntity.getFreightReducedValue());
                                            tips.add("满"+promotionEntity.getFreightValue().longValue()+"元减"+promotionEntity.getFreightReducedValue()+"元运费");
                                        }
                                    }
                                }
                            }
                        }else if(promotionEntity.getPromType()==7){
                            PromotionRuleEntity promotionRuleEntity = promotionRuleEntityMapper.queryPromotionRuleById(promotionEntity.getId());
                            if(null!=promotionRuleEntity){
                                //单品X件优惠
                                if(promotionEntity.getFreightType()==12){
                                    //第X件Y折
                                    if(promotionRuleEntity.getConditionValue().longValue()<=new BigDecimal(num).longValue()){
                                        //优惠金额
                                        BigDecimal subtract = marketResponse.getMarketPrice().subtract(marketResponse.getMarketPrice().multiply(promotionRuleEntity.getContentValue().divide(new BigDecimal(100))));
                                        marketResponse.setDiscountPrice(marketResponse.getDiscountPrice().add(subtract));
                                        //总金额减去优惠抵扣金额
                                        marketResponse.setMarketPrice(marketResponse.getMarketPrice().multiply(new BigDecimal(num-1)).add(marketResponse.getMarketPrice().multiply(promotionRuleEntity.getContentValue().divide(new BigDecimal(100)))));
                                        tips.add("满"+promotionRuleEntity.getConditionValue()+"件"+promotionRuleEntity.getContentValue().divide(new BigDecimal(100))+"折");
                                    }
                                }else if(promotionEntity.getFreightType()==13){
                                    //第X 件Y元
                                    if(promotionRuleEntity.getConditionValue().longValue()<=new BigDecimal(num).longValue()){
                                        //优惠金额
                                        marketResponse.setDiscountPrice(marketResponse.getDiscountPrice().add(promotionRuleEntity.getContentValue().divide(new BigDecimal(100))));
                                        //总金额减去优惠抵扣金额
                                        marketResponse.setMarketPrice(marketResponse.getMarketPrice().multiply(new BigDecimal(num-1)).add(marketResponse.getMarketPrice().subtract(promotionRuleEntity.getContentValue().divide(new BigDecimal(100)))));
                                        tips.add("第"+promotionRuleEntity.getConditionValue()+"件"+promotionRuleEntity.getContentValue().divide(new BigDecimal(100))+"元");
                                    }
                                }else if(promotionEntity.getFreightType()==14){
                                    //满X件Y折
                                    if(promotionRuleEntity.getConditionValue().longValue()<=new BigDecimal(num).longValue()){
                                        //优惠金额
                                        BigDecimal subtract = marketResponse.getMarketPrice().subtract((marketResponse.getMarketPrice()).multiply(promotionRuleEntity.getContentValue().divide(new BigDecimal(100))));
                                        marketResponse.setDiscountPrice(marketResponse.getDiscountPrice().add(subtract));
                                        //总金额减去优惠抵扣金额
                                        marketResponse.setMarketPrice((marketResponse.getMarketPrice()).multiply(promotionRuleEntity.getContentValue().divide(new BigDecimal(100))));
                                        tips.add("满"+promotionRuleEntity.getConditionValue()+"件"+promotionRuleEntity.getContentValue()+"折");
                                    }
                                }
                            }
                        }
                    }
                    marketResponse.setMarketTips(String.join(",",tips));
                }
            }
        }
        return marketResponse;
    }
}
